package atguigu.jdbc;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;

import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {


    public static void main(String[] args) {

        DruidDataSource dataSource = DruidConfig.createDataSource();
        try {
            DruidPooledConnection connection = dataSource.getConnection();
            List<String> paramList = new ArrayList<>();
            try {
                String sql =
                        " select applianceid ,error_code ,error_flag ,error_flag ,productid ,sn " +
                        " from b0_reportdata_04 where applianceid = ? ";
                paramList.add("1232");
                List<Map<String, Object>> objects = queryForVectorHandle(connection, sql, paramList.toArray());
                for (Map<String, Object> map : objects) {
                    map.get("applianceid");
                    map.get("productid");
                    map.get("error_code");
                    map.get("error_flag");
                    map.get("sn");

                }
            }catch (Exception e){

            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void setPreparedStatementParams(PreparedStatement stmt, Object[] objects) throws SQLException {
        for (int i = 1; i <= objects.length; i++) {
            Object obj = objects[i - 1];

            if (obj == null) {
                stmt.setString(i, "");
                continue;
            }

            if (obj instanceof String) {
                stmt.setString(i, (String) obj);
            } else if (obj instanceof Timestamp) {
                stmt.setTimestamp(i, (Timestamp) obj);
            } else if (obj instanceof Date) {
                stmt.setDate(i, (Date) obj);
            } else if (obj instanceof Integer) {
                stmt.setInt(i, ((Integer) obj).intValue());
            } else if (obj instanceof Double) {
                stmt.setDouble(i, ((Double) obj).doubleValue());
            } else if (obj instanceof Long) {
                stmt.setLong(i, ((Long) obj).longValue());
            } else if (obj instanceof BigDecimal) {
                stmt.setBigDecimal(i, ((BigDecimal) obj));
            }
        }
    }


    public static Object setNullObjectDefualValue(int type, Object object) {
        if (null == object) {
            switch (type) {
                case Types.VARCHAR:
                    object = new String();
                    break;
                case Types.INTEGER:
                    object = new Integer(0);
                    break;
                case Types.DOUBLE:
                    object = new Double(0);
                    break;

                case Types.FLOAT:
                    object = new Float(0);
                    break;

                case Types.NUMERIC:
                    object = new BigDecimal(0);
                    break;

                default:
                    break;
            }
        }
        return object;
    }

    public static List<Map<String, Object>> queryForVectorHandle(Connection connection,String sql, Object... objects) throws Exception {
        PreparedStatement stmt = null;
        Connection conn = null;
        ResultSet rs = null;
        try {
            conn = connection;
            stmt = conn.prepareStatement(sql);
            if(objects!=null) {
                setPreparedStatementParams(stmt, objects);
            }
            rs = stmt.executeQuery();
            List<Map<String, Object>> v = new ArrayList();

            while (rs.next()) {

                Map<String, Object> map = new HashMap<String, Object>();
                ResultSetMetaData meta = rs.getMetaData();

                setRowDataToMap(rs, map, meta);

                v.add(map);

            }
            return v;

        } catch (SQLException e) {
            throw new Exception(e.getLocalizedMessage());
        } finally {
            releaseSqlConnection(rs, stmt, null, conn);
        }
    }

    public static void setRowDataToMap(ResultSet rs, Map<String, Object> map, ResultSetMetaData meta) throws SQLException {
        for (int i = 1; i <= meta.getColumnCount(); i++) {

            int type = meta.getColumnType(i);
            Object object = rs.getObject(i);

            if (type == Types.VARCHAR && null == object)
                object = new String();

            if ((type == Types.INTEGER || type == Types.DOUBLE || type == Types.FLOAT || type == Types.NUMERIC) && null == object)
                object = "0";
            String columnName = meta.getColumnLabel(i) != null && meta.getColumnLabel(i).length() > 0 ? meta.getColumnLabel(i) : meta.getColumnName(i);
            map.put(columnName.toLowerCase(), object);
        }
    }
    public static List<Object> queryForListHandle(Connection connection,String sql, Object... objects) throws Exception {
        PreparedStatement stmt = null;
        Connection conn = null;
        ResultSet rs = null;
        try {
            conn = connection;
            stmt = conn.prepareStatement(sql);
            setPreparedStatementParams(stmt, objects);
            rs = stmt.executeQuery();

            List<Object> list = new ArrayList<Object>();
            while (rs.next()) {
                ResultSetMetaData meta = rs.getMetaData();
                if (meta.getColumnCount() >= 1) {
                    int type = meta.getColumnType(1);
                    Object object = rs.getObject(1);
                    object = setNullObjectDefualValue(type, object);
                    list.add(object);
                }
            }
            return list;

        } catch (SQLException e) {
            throw new Exception(e.getLocalizedMessage());
        } finally {
            releaseSqlConnection(rs, stmt, null, conn);

        }
    }

    /**
     * 关闭数据库连接实例
     */
    public static void releaseSqlConnection(ResultSet rSet, PreparedStatement pStatement, Statement iStatement, Connection connection) {
        try {
            if (rSet != null) {
                rSet.close();
            }
        } catch (SQLException e) {
        } finally {
            try {
                if (pStatement != null) {
                    pStatement.close();
                }
                if (iStatement != null) {
                    iStatement.close();
                }
            } catch (SQLException e) {
            } finally {
                try {
                    if (connection != null) {
                        connection.close();
                    }
                } catch (SQLException e) {
                }
            }
        }
    }

}
